package com.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.ArrayList;
import java.util.List;

import com.entity.Product;
import com.form.Main1Form;

public class Main1Action extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		List<Product> productList = null;

		Main1Form main1Form = (Main1Form) form;

		String select1 = main1Form.getSelect1();
		String select2 = main1Form.getSelect2();
		String select3 = main1Form.getSelect3();
		String keyword = main1Form.getKeyword();

		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/shangpin";
		String user = "root";
		String password = "rosy";

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, password);
			Statement stmt = conn.createStatement();
			String sql = "select * from product where" + "(" + "ProductKbnA ='"
					+ select1 + "'" + "AND" + " ProductKbnB ='" + select2 + "'"
					+ "AND" + " ProductKbnC ='" + select3 + "'" + ")" + " AND"
					+ " ProductName like '" + "%" + keyword + "%" + "'";

			ResultSet rs = stmt.executeQuery(sql);

			// 検索したデータを 配列 class にセット

			productList = new ArrayList<Product>();
			while (rs.next()) {
				Product product = new Product();
				product.setProductId(rs.getString("ProductId"));
				product.setProductKbnA(rs.getString("ProductKbnA"));
				product.setProductKbnB(rs.getString("ProductKbnB"));
				product.setProductKbnC(rs.getString("ProductKbnC"));
				product.setMaker(rs.getString("Maker"));
				product.setProductName(rs.getString("ProductName"));

				productList.add(product);
			}

			rs.close();
			stmt.close();
			// pstmt.close();
			conn.close();

			// throw new SQLException();

		} catch (ClassNotFoundException e) {
			System.out.println("Class not found");
		} catch (SQLException e) {
			System.out.println("Sql exception");
		} catch (Exception e) {
			System.out.println("exception");
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				response.getWriter().println(e.getMessage());
			}
		}

		request.setAttribute("products", productList);

		return mapping.findForward("success");

	}
}
